<template>
    <div>
        <h1>图书管理系统</h1>
        <div style="margin: 30px;">
            <button @click="addNew">新增图书</button>
            <bookhead v-show='dialogVisible'
            :visible.sync="dialogVisible"
            :data='editData'
            @save='save'
            ></bookhead>
        </div>
        <table style='margin: auto; border: solid 1px black;'>
            <tr>
                <td>图书编号</td>
                <td>图书名字</td>
                <td>出版时间</td>
                <td>阅读数</td>
                <td>评论数</td>
                <td>操作</td>
                <td>操作</td>
            </tr>
            <tr v-for='(i,index) in books' :key="index">
                <td>{{i.id}}</td>
                <td>{{i.btitle}}</td>
                <td>{{i.bpub_date}}</td>
                <td>{{i.bread}}</td>
                <td>{{i.bcomment}}</td>
                <td><button @click="edit(index)">修改</button></td>
                <td><button @click="del(index)">删除</button></td>
            </tr>

        </table>
    </div>
</template>

<script>
import bookhead from '@/components/bookhead'
import { getbooks,postbooks,delbooks,putbooks } from '@/http/api'
export default {
data() {
    return {
       books:[],
       editData:{//编辑的内容
       btitle:"",
       bpub_date:"",
       bread:0,
       bcomment:0

       },
       dialogVisible: false,

    }
},components:{
    bookhead,
},
methods: {
    show(){
        getbooks().then(res=>{
            console.log(res);
            this.books=res.data
        
        })
    },
    edit(index){
        this.editData = JSON.parse(JSON.stringify(this.books[index]))  // 复制 this.books[index] 的数据
      // this.editData = this.books[index]  // 
      this.dialogVisible = true
    },
    addNew(){
        this.editData = { //初始化 编辑
         btitle: "",
        bpub_date: "",
        bread: 100,
        bcomment: 0

        }
        this.dialogVisible = true //显示弹框
    },
    save(){
        // 根据editData中的id判断是更新还是新增
      // debugger
      console.log(this.editData)
      if (this.editData.id) {
        // 如果有id, 修改图书
        // 修改请求
        let params = this.editData
        putbooks(params).then((res)=>{
          console.log(res)
          this.show()
        })
      } else {
        // 增加图书
        postbooks(this.editData).then((res) => {
          this.show()
        })
      }
    },
    del(index){
        let params = {
        id: this.books[index].id
      }
      delbooks(params).then((res)=>{
        console.log(res)
        this.show()
      })

    }


},
created() {
    this.show();

},
}
</script>


<style>
table tr td {
  width: 150px;
  border: solid 1px black;
}
</style>
